package no.zsoft.faktura.admin.service;

import java.util.List;

import no.zsoft.faktura.admin.domain.Authority;
import no.zsoft.faktura.admin.domain.User;
import no.zsoft.faktura.admin.domain.UserRole;
import no.zsoft.faktura.admin.repository.TenantRepository;
import no.zsoft.faktura.admin.repository.UserRepository;
import no.zsoft.faktura.admin.repository.UserRoleRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServices {
	@Autowired
	UserRepository userRepository;
	@Autowired
	UserRoleRepository roleRepository;
	
	@Autowired
	TenantRepository tenantRepository;
	public void creatNewUser(User user, List<String> roles) {
		userRepository.save(user);
		for (String authority : roles) {
			List<UserRole> role = roleRepository.findByAuthority(Authority
					.valueOf(Authority.class, authority));
			if (role != null && !role.isEmpty()) {
				user.getRoles().add(role.get(0));
			}
			user.setEnabled(true);
			userRepository.save(user);
		}

	}

	public void deleteUser(User user) {
		System.err.println("*************" + user);

		userRepository.delete(user);
	}

	public List<User> getAllUsers() {
		return userRepository.findAll();
	}

	public boolean userNameExists(String userName) {
		return userRepository.findByUserName(userName).isEmpty() ? false : true;
	}

	public User getUser(String name) {

		List<User> findByUserName = userRepository.findByUserName(name);
		if (findByUserName != null && !findByUserName.isEmpty()) {
			return findByUserName.get(0);
		}
		return null;
	}

	public User update(User user) {
		return userRepository.save(user);
	}

	public boolean isTenantNameAvailable(String tenant) {
		
		return userRepository.findByTenant(tenant).isEmpty();
	}
	public void createTenant(String tenant){
		tenantRepository.createTenant(tenant);
	}
}
